<template>
  <div>
    <baidu-map
      ref="bmap"
      :style="{ height: options.height }"
      class="map"
      :center="centers"
      :zoom="zoom"
      :map-type="mapType"
      :scroll-wheel-zoom="true"
      @ready="handler"
      :map-click="false"
    >
      <bml-marker-clusterer :average-center="true">
        <div :key="m.deviceCode" v-for="m in markers">
          <bm-marker
            :position="m.position"
            :icon="m.icon"
            @click="openInfoWindowClick1(m)"
          >
            <bm-label
              :content="m.label.text"
              :labelStyle="{
                color: '#fff',
                fontSize: '12px',
                background: '#000',
                borderRadius: '10px',
                padding: '2px 5px',
                border: 'none',
                textAlign: 'center'
              }"
              :offset="{ width: 0, height: 50 }"
            />
          </bm-marker>
        </div>
      </bml-marker-clusterer>

      <bm-info-window
        v-if="infoWinPos"
        :closeOnClick="false"
        :position="infoWinPos"
        :show="isOpenInfoWin"
        autoPan
        @close="closeInfoWindow"
        @open="1"
      >
        <div v-if="options.infos && options.infos.alarmTypeName">
          <p>{{ options.infos.alarmTypeName }}</p>
          <p>{{ parseTime(options.infos.time) }}</p>
        </div>
        <Infowindow :form="markerInfo" />
      </bm-info-window>

      <!-- 分段轨迹 -->
      <bm-polyline
        :path="sectionPath"
        :stroke-color="secLineOptions.color"
        :stroke-opacity="secLineOptions.opacity"
        :stroke-weight="secLineOptions.weight"
      >
      </bm-polyline>

      <template
        v-if="vehicleMarkers && vehicleMarkers.length && pointsMarker[0]"
      >
        <bm-marker
          :position="pointsMarker[0].position"
          :icon="pointsMarker[0].icon"
        >
        </bm-marker>
        <bm-marker
          :position="pointsMarker[1].position"
          :icon="pointsMarker[1].icon"
        >
        </bm-marker>

        <bml-lushu
          :path="vehicleMarkers"
          :icon="currUrl"
          :play="play"
          :speed="speed"
          :rotation="false"
          :autoView="true"
        >
        </bml-lushu>
      </template>

      <bm-control v-if="!options.isSearch">
        <bm-auto-complete
          ref="autocomplete"
          v-model="keyword"
          :sugStyle="{ zIndex: 1 }"
          @confirm="handleAutocomplete"
        >
          <el-input
            @focus="handleFocus"
            placeholder=""
            style="width: 100%"
            v-model="searchValue"
          ></el-input>
          <!-- 这里指代一个自定义搜索框组件 -->
        </bm-auto-complete>
      </bm-control>
      <bm-marker
        :key="index"
        v-for="(m, index) in searchMarker"
        :position="m.position"
        :icon="m.icon"
      >
      </bm-marker>
    </baidu-map>
  </div>
</template>

<script>
import Vue from "vue";
import { vehicleMonitorDetail } from "@/api/vehicle/position/data";
import BaiduMap from "vue-baidu-map";
import Infowindow from "./Infowindow";
import {
  BmlMarkerClusterer,
  BmInfoWindow,
  Convertor,
  BmlLushu,
} from "vue-baidu-map";
Vue.use(BaiduMap, {
  ak: "SmO6CT9A18BmsoakcPyh33ApwCpRMr4w",
  // ak:"16bce25548fd79260a60126e103ea160"
});

export default {
  name: "Baidu",
  components: {
    BmlMarkerClusterer,
    BmInfoWindow,
    Infowindow,
    BmlLushu,
  },
  props: {
    options: {
      type: Object,
      default: () => {
        return {
          position: { lat: 51.5073509, lng: -0.1277583 },
          isSearch: false, //是否显示搜索框
          showInfo: false, //是否显示信息弹框
          isTrack: false, //是否显示轨迹
          height: "300px", //地图的高度
          posList: [], //gps数组,
          trackList: [],
          infos: {}, //信息弹框的内容
          address: "", //地址
        };
      },
    },
  },
  watch: {
    options: {
      handler: function (val) {
        this.posList = val.posList;
        console.log(val.posList);
        if(val.mapType == 'roadmap'){
          this.mapType = 'BMAP_NORMAL_MAP'
        }else{
          this.mapType = 'BMAP_HYBRID_MAP'
        }

       
        const fn = (position) => {
          const centers = position || val.position;
          if (val.showInfo) {
            this.infoWindow.position = centers;
            this.infoWindow.show = val.showInfo;
            this.centers = centers;
          }
          if (val.isSearch) {
            this.searchMarker = [];
            this.searchMarker.push({ position: this.centers });
            this.searchValue = val.address;
            this.centers = centers;
          }

          if (val.isTrack && val.trackList.length) {
            this.$nextTick(() => {
              const newPosList = val.trackList.filter(
                (item) => item.lat && item.lng
              );

              const points = newPosList.map((_) => {
                return {
                  lat: _.lat,
                  lng: _.lng,
                };
              });

              var allPoint = []; //转换后的点数组
              var translatePoint = []; //中转数组
              for (var i = 0; i < points.length; i += 10) {
                translatePoint.push(points.slice(i, i + 10)); //  从已有的数组中返回选定的元素,该方法并不会修改数组，而是返回一个子数组
              }
              const promises = translatePoint.map((_) => {
                return new Promise((res) => {
                  this.convertor.translate(_, 1, 5, (data) => {
                    res(data.points);
                  });
                });
              });
              Promise.all(promises).then((res) => {
                res.forEach((_) => {
                  allPoint = allPoint.concat(_);
                });

                newPosList.forEach((_, index) => {
                  _ = { ..._, ...allPoint[index] };
                });
                this.sectionPath = newPosList;

                this.pointsMarker = this.setStartEndPoint(this.sectionPath);
                const { vehicleMakers1, url } = this.setMoveVehicle(
                  this.sectionPath,
                  true
                );
                this.vehicleMarkers = vehicleMakers1;
                this.currUrl = {
                  size: { width: 39, height: 55 },
                  opts: { anchor: { width: 22, height: 42 } },
                  url,
                };
                const point = this.sectionPath.map((_) => {
                  return new this.bmap.Point(_.lng, _.lat);
                });
                var view = this.map.getViewport(point);
                var mapZoom = view.zoom;

                var centerPoint = view.center;
                this.map.centerAndZoom(centerPoint, mapZoom);
              });
            });
          }

          if (val.posList && val.posList.length) {
            const newPosList = val.posList.filter(
              (item) => item.lat && item.lng
            );
            const points = newPosList.map((_) => {
              return {
                lat: _.lat,
                lng: _.lng,
              };
            });

            var allPoint = []; //转换后的点数组
            var translatePoint = []; //中转数组
            for (var i = 0; i < points.length; i += 10) {
              translatePoint.push(points.slice(i, i + 10)); //  从已有的数组中返回选定的元素,该方法并不会修改数组，而是返回一个子数组
            }

            const promises = translatePoint.map((_) => {
              return new Promise((res) => {
                this.convertor.translate(_, 1, 5, (data) => {
                  res(data.points);
                });
              });
            });
            Promise.all(promises).then((res) => {
              res.forEach((_) => {
                allPoint = allPoint.concat(_);
              });

              newPosList.forEach((_, index) => {
                _ = { ..._, ...allPoint[index] };
              });

              const { vehicleMakers } = this.setMoveVehicle(newPosList);
              this.markers = vehicleMakers;
              this.oMarkers = [...this.markers];
              this.$nextTick(() => {
                   this.zoom = 5;
              });
            });
          }
        };

        setTimeout(() => {
          const center = val.position ? [val.position] : [];
          if (center.length) {

            this.convertor.translate(center, 1, 5, (position) => {
              fn(position);
              let point = new BMap.Point(116.514,39.91 );
              this.map.centerAndZoom(point, 5);
              this.map.panTo(point); //平
            });
          } else {
            fn();
            let point = new BMap.Point(116.514,39.91 );
              this.map.centerAndZoom(point, 5);
              this.map.panTo(point); //平滑到以点开的标记的经纬度为中心点的地方

          }
        }, 1000);
        //再次渲染
        console.log(val.isJourney);
        if (val.isJourney) {
        }else{
          setTimeout(() => {
            let point = new BMap.Point(116.924,39.91 );
              this.map.centerAndZoom(point, 5);
              this.map.panTo(point); //平滑到以点开的标记的经纬度为中心点的地方
        }, 2000);
        }
        
       
      },
      immediate: true,
      deep: true,



    },
  },
  data() {
    return {
      cancel:0,
      map: null,
      convertor: null,
      vehicleMarkers: [],
      icon: {
        url: "http://api.map.baidu.com/library/LuShu/1.2/examples/car.png",
        size: { width: 52, height: 26 },
        opts: { anchor: { width: 27, height: 13 } },
      },
      bmap: null,
      play: false,
      speed: 0,
      currUrl: "",
      centers: {
        lng: 116.514,
        lat: 39.91,
      },
      zoom: 5,
      isOpenInfoWin: false,
      markerss: [],
      pointsMarker: [],
      moveVehicleMarkers: [],
      alarmsMarker: [],
      icons: [
        require("@/assets/images/onLine.png"),
        require("@/assets/images/offLine.png"),
        require("@/assets/images/park.png"),
      ],
      markers: [],
      sectionPath: [],
      secLineOptions: {
        color: "#029801",
        weight: 4,
        opacity: 1,
      },
      mapType: "BMAP_NORMAL_MAP",
      searchMarker: [],
      keyword: "",
      markerInfo: {},
      infoWinPos: null,
      searchValue: "",
      infoWindow: {
        position: { lng: 0, lat: 0 },
        show: false,
      },
    };
  },
  created() {},
  mounted() {},
  methods: {
    //设置起始点标记
    setStartEndPoint(list) {
      let points = [];
      //起始点
      let sPoint = {
        position: {
          lng: parseFloat(list[0].lng),
          lat: parseFloat(list[0].lat),
        },
        icon: {
          url: require("@/assets/images/startNew.png"),
          size: { width: 30, height: 40 },
        },
        name: "start" + list[0].direction,
      };
      //结束点
      let ePoint = {
        position: {
          lng: parseFloat(list[list.length - 1].lng),
          lat: parseFloat(list[list.length - 1].lat),
        },
        icon: {
          url: require("@/assets/images/endNew.png"),
          size: { width: 30, height: 40 },
        },
        name: "end" + list[0].direction,
      };
      points.push(sPoint, ePoint);
      return points;
    },
    handler({ BMap, map }) {
      map.clearOverlays();
      this.map = map;
      this.bmap = BMap;
      this.convertor = new BMap.Convertor();
    },
    handleAutocomplete() {
      this.searchMarker = [];
      const geoCoder = new BMap.Geocoder();
      // 获取位置对应的坐标
      geoCoder.getPoint(this.keyword, (point) => {
        this.centers = {
          lng: point.lng,
          lat: point.lat,
        };
        this.zoom = 15;
        this.searchMarker.push({ position: this.centers });
      });
      const params = {
        address: this.keyword,
        position: this.centers,
      };
      this.$emit("searchAddress", params);
    },
    closeInfoWindow() {},
    openInfoWindowClick1(item) {
      console.log(item);
       // 逆解析地址
      // this.isOpenInfoWin = false;
      vehicleMonitorDetail({ deviceCode: item.deviceCode }).then((res) => {
        if (res.data.lat != null || res.data.lng != null) {
                        
          this.convertor.translate(
            [{ lng: res.data.lng, lat: res.data.lat }],
            1,
            5,
            ({ points }) => {
              this.markerInfo = res.data;
              this.isOpenInfoWin = true;
              this.infoWinPos = points[0];
              // this.centers = points[0];
              this.map.panTo(points[0]); //平滑到以点开的标记的经纬度为中心点的地方
              // this.zoom = 17;

              // this.map = new window.BMapGL.Map(this.$refs.maps);
            
              // var point = new window.BMapGL.Point(116.404, 39.915);
              //  map.centerAndZoom(point, 15);
              //  map.enableScrollWheelZoom(true);
              //  map.setMapType(window.BMAP_EARTH_MAP);
                        

            }
          );
        }else if(this.cancel == 0 &&
          (res.data.lat == null || res.data.lng == null)){
            this.msgSuccess(this.$t("prompt.noGps"));
            this.cancel++;
          }else{
            this.cancel = 0;
          }

        // if (
        //   this.cancel == 0 &&
        //   (res.data.lat == null || res.data.lng == null)
        // ) {
        //   this.msgSuccess(this.$t("prompt.noGps"));
        //   this.cancel++;
        // } else {
        //   this.cancel = 0;
        // }
      });
    },
    togglePlay(play, speed) {
      this.play = play;
      this.speed = speed;
    },
    handleFocus() {
      document.querySelector(".tangram-suggestion-main").style.display =
        "block";
    },
    //设置车辆位置标记, isMove:表示移动车辆
    setMoveVehicle(list, isMove = false) {
      let vehicleMakers = [];
      let vehicleMakers1 = [];

      let url = "";
      list.forEach((item) => {
        if (item.lat || item.lng) {
          if (!url) {
            url =
              item.state === 1
                ? this.icons[1]
                : item.state === 2
                ? this.icons[0]
                : this.icons[2];
          }
          let vMarker = {
            deviceCode: !isMove ? item.deviceCode : undefined,
            title: !isMove ? item.vehicleType : undefined,
            position: {
              lat: item.lat,
              lng: item.lng,
            },
            icon: {
              url: isMove ? this.icons[0] : url,
              size: {
                width: 39,
                height: 55,
              },
              labelOrigin: { x: 20, y: 70 },
              // scaledSize: new google.maps.Size(39, 55)
            },
            name: "vehicle" + item.direction,
            content: isMove ? "" : item,
            visible: true,
            label: isMove
              ? ""
              : {
                  color: "#ffffff",
                  className: "map_label",
                  text: item.vehicleType,
                },
          };
          vehicleMakers1.push({
            lat: item.lat,
            lng: item.lng,
          });
          vehicleMakers.push(vMarker);
        }
      });
      return { vehicleMakers1, vehicleMakers, url };
    },
    //车辆移动
    handleVehicleMove(index, flag) {
      if (index >= this.vehicleMarkers.length) {
        return;
      }
      this.moveVehicleMarkers = [];
      this.moveVehicleMarkers.push(this.vehicleMarkers[index]);
      if (!this.boundCenter.contains(this.vehicleMarkers[index].position)) {
        this.centers = this.vehicleMarkers[index].position;
        this.map.panTo(this.vehicleMarkers[index].position);
      }
    },
    openInfoWindowClickOneMore(item) {
   
      vehicleMonitorDetail({ deviceCode: item.deviceCode }).then((res) => {
        if (res.data.lat || res.data.lng) {  

          this.convertor.translate(
            [{ lng: res.data.lng, lat: res.data.lat }],
            1,
            5,
            ({ points }) => {
              this.markerInfo = res.data;
              this.isOpenInfoWin = true;
              this.infoWinPos = points[0];
              // // this.centers = points[0];
              // this.map.panTo(points[0]); //平滑到以点开的标记的经纬度为中心点的地方
              // // this.zoom = 17;
              // baiduMap.setMyLocationEnabled(true);
              let point = new BMap.Point(res.data.lng,res.data.lat );
              this.map.centerAndZoom(point, 25);
              this.map.panTo(points[0]); //平滑到以点开的标记的经纬度为中心点的地方

          // this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放

        //   const _this = this;
        // const geolocation = new BMap.Geolocation();
        // geolocation.getCurrentPosition(function (r) {
        //   if (this.getStatus() == BMAP_STATUS_SUCCESS) {
        //     _this.handleMarker(_this, r.point);
        //     let myGeo = new BMap.Geocoder();
        //     myGeo.getLocation(
        //       new BMap.Point(r.point.lng, r.point.lat),
        //       function (result) {
        //         _this.confirmLoading = false;
        //         if (result) {
        //           _this.latitude = result.point.lat;
        //           _this.longitude = result.point.lng;
        //         }
        //       }
        //     );
        //   } 
        // });

                        

                        
            }
          );
            // console.log("有");
        }else if (
          this.cancel == 0 &&
          (res.data.lat == null || res.data.lng == null)
        ) {
          // console.log("没有");
          this.$modal.msgError(this.$t("vehicle.position.noGps"));
          this.cancel++;
        } else {
          console.log("最后");
          this.$modal.msgError(this.$t("vehicle.position.noGps"));
          this.cancel = 0;
        }
      });
    },
   
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 300px;
  margin-top: 10px;
}
.anchorTL {
  width: 100%;
}
</style>
